<template>
  <form-dialop
    :title="$t('common.edit')"
    :visible="visible"
    width="50%"
    @handleClose="handleClose"
		v-loading="loading"
  >
    <template #content>
      <el-form ref="form" :model="formData" label-position="left" :rules="formRule">
        <el-form-item :label="$t('markdowns.classify')" prop="title" name="title">
          <el-input v-model="formData.title" @keyup.enter.native="submit"></el-input>
        </el-form-item>
        <div id="ed_markdown" ref="ed_markdown" >
          <div v-html="htmlData"></div>
        </div>
      </el-form>

    </template>
    <template #footer>
      <el-button @click="handleClose">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" @click="submit" :disabled="loading">{{ $t('common.confirm') }}</el-button>
    </template>
  </form-dialop>
</template>
<script lang="ts">
import Vue from 'vue'
import FormDialop from '@/components/Dialog/formDialog.vue';
import { AuthModule } from '@/store/modules/auth';
import E from 'wangeditor';
import sparkMd5 from 'spark-md5'
export default Vue.extend({
  components: {
    FormDialop
  },
  props: {
    patchMethod: {
      type: Function,
      default() {
        return () => Promise.resolve();
      }
    }
  },
  data() {
    return {
      visible: false,
      loading: false,
      formData: {
        title: ''
      },
      md_id: '',
      ed: '',
      htmlData: '',
      formRule: {
        title:[
          { required: true, message: this.$t('markdowns.classifyTips'), trigger: 'blur' },
          { type: 'string', min: 1, max: 30, message: this.$t('markdowns.classifyLengthTips'), trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    initMD(row: any) {
      (this as any).ed = new E('#ed_markdown');
      (this as any).ed.config.showFullScreen = false;
      (this as any).ed.config.menus = ['head','bold','fontName','fontSize','italic','underline','strikeThrough','indent','lineHeight','foreColor','backColor','link','list','todo','justify','quote','image','table','code','splitLine','undo','redo'];
      (this as any).ed.config.uploadImgServer = '/panda/faq/image/update';
      const that = this;
      (this as any).ed.config.customUploadImg = (resultFiles: any, insertImgFn: any) => {
        const fileReader = new FileReader()
        fileReader.readAsBinaryString(resultFiles[0]);
        fileReader.onload = (e: any) => {
          const md5 = sparkMd5.hashBinary(e.target.result);
          const headers = {
            "markdown-md5": md5,
            "Content-Disposition": "attachment;filename=" + encodeURIComponent(resultFiles[0].name),
            "Content-Type": "application/json"
          };
          that.$pandaApi.apiUploadImgs(resultFiles[0], headers).then((res: any) => {
            if(res.errno == 0 && res.data.length > 0) {
              insertImgFn(res.data[0].url);
            }
          }).catch((err: any)=>{
            console.log(err)
          })
        }
      };
      (this as any).ed.create();
      
    },
    init(row: any) {
      this.tenant_options = [];
			this.formData = {
					title: row.name
			};
      this.md_id = row.id
      this.htmlData = row.content
      this.$nextTick(() => {
        if(!this.ed)
          this.initMD(row)
        if (this.$refs['form']) {
          (this.$refs['form'] as any).clearValidate();
        }
        (this as any).ed.txt.html(row.content);
      })
      this.visible = true;
    },
    submit() {
      (this.$refs.form as any).validate((valid: any) => {
        if (valid) {
          if(!(this as any).ed.txt.html()) {
            this.$message.warning((this as any).$t('markdowns.contentTips'))
            return ;
          }
					this.loading = true;
          (this as any).patchMethod(this.md_id,{
            "name": this.formData.title,
            "content": (this as any).ed.txt.html()
          }).then(() => {
            (this as any).visible = false;
          }).finally(() => {
            (this as any).loading = false;
          });
        }
      });
    },
    handleClose() {
      this.formData = {
        title: ""
      };
      this.htmlData = "";
      this.md_id = "";
      // (this as any).ed.txt.clear();
      this.visible = false;
			this.loading = false;
      (this as any).ed.txt.clear();
    }
  }
})
</script>
<style scoped>
#ed_markdown {
  margin-left: 53px;
}
</style>
